<?php

namespace app\common\model\mycurrency;

use addons\epay\library\Service;
use addons\mycurrency\library\Common;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;
use Yansongda\Pay\Pay as yan_pay;
use addons\epay\library\Collection as yan_collection;

class Pay extends Model
{

    //use SoftDelete;


    // 表名
    protected $name = 'mycurrency_pay';

    const PAY_TYPE_WECHAT = 1;//支付方式 = 微信支付
    const PAY_TYPE_ALIPAY = 2;//支付方式 = 支付宝支付

    const ORDER_TYPE_YUE = 1;//订单类型 = 用户余额充值订单
    const ORDER_TYPE_YAJIN = 2;//订单类型 = 租赁订单押金支付
    const ORDER_TYPE_ZULINFEIYONG = 3;//订单类型 = 租赁订单租赁费用支付


    const STATUS_CHAOSHI = -1;//支付状态 = 支付超时
    const STATUS_QUXIAO = -2;//支付状态 = 已取消
    const STATUS_DAIZHIFU = 1;//支付状态 = 待支付
    const STATUS_YIZHIFU = 2;//支付状态 = 已支付

    const REFUND_TYPE_SHIBAI = -1;//退款状态:-1=退款失败
    const REFUND_TYPE_WEITUIKUAN = 0;//退款状态:0=未退款
    const REFUND_TYPE_TUIKUANZHONG = 1;//退款状态:1=退款中
    const REFUND_TYPE_YITUIKUAN = 2;//退款状态:2=退款完成

    /**
     * 生成支付单单号
     * @return string
     */
    public static function createPayOrderSn()
    {
        $payOrderSn = date('YmdHis') . mt_rand(1000, 9999);
        $exists = self::where('refund_id', $payOrderSn)->value('id');
        if (!$exists) {
            return $payOrderSn;
        }
        return self::createPayOrderSn();
    }

    /**
     * 生成退款单号
     * @return string
     */
    public static function requestNo()
    {
        $payOrderSn = date('YmdHis') . mt_rand(1000, 9999);
        $exists = self::where('out_refund_no', $payOrderSn)->value('id');
        if (!$exists) {
            return $payOrderSn;
        }
        return self::requestNo();
    }


    /**
     * 提交退款订单
     * @param array|float $amount    订单金额
     * @param array|float $refund_money    退款金额
     * @param string      $orderid   订单号
     * @param string      $refund_sn   退款订单号
     * @param string      $type      支付类型,可选alipay或wechat
     * @param string      $remark     退款原因
     * @param string      $notifyurl 通知回调URL
     * @param string      $returnurl 跳转返回URL
     * @param string      $method    支付方式
     * @return Response|RedirectResponse|Collection
     * @throws Exception
     */
    public static function submitRefund($amount=null,$refund_money,$orderid,$refund_sn,$type,$remark = null,$notifyurl = null,$returnurl = null,$method = 'app'){
        if (!is_array($amount)) {
            $params = [
                'amount'    => $amount,
                'type'      => $type,
                'notifyurl' => $notifyurl,
                'returnurl' => $returnurl,
                'method'    => $method,
            ];
        } else {
            $params = $amount;
        }

        $type = isset($params['type']) && in_array($params['type'], ['alipay', 'wechat']) ? $params['type'] : 'wechat';
        $request = request();
        $notifyurl = isset($params['notifyurl']) ? $params['notifyurl'] : $request->root(true) . '/addons/epay/index/' . $type . 'notify';
        // $returnurl = isset($params['returnurl']) ? $params['returnurl'] : $request->root(true) . '/addons/epay/index/' . $type . 'return/out_trade_no/' . $orderid;
        $config = Service::getConfig($type);

        $config['notify_url'] = $notifyurl;
        $config['return_url'] = $returnurl;
        $result = null;
        //退款参数
        $order_data = [
            'out_trade_no' => $orderid//原订单号
        ];
        if ($type == 'wechat') {
            //创建支付对象
            $pay = yan_pay::wechat($config);
            $total_fee = $amount * 100;
            $refund_fee = $refund_money * 100;
            $order_data = array_merge($order_data, [
                'out_refund_no' => $refund_sn,//退款订单号
                'total_fee' => $total_fee,//支付金额
                'refund_fee' => $refund_fee,//退款金额
                'refund_desc' => $remark,//退款原因
                'type' => $method  //支付方式
            ]);
        } else {
            $pay = yan_pay::alipay($config);
            $order_data = array_merge($order_data, [
                'out_request_no' => $refund_sn,//退款订单号
                'refund_amount' => $refund_money,
            ]);
        }

        $result = $pay->refund($order_data);
        trace('========================开始处理结束订单42-6 开始执行线上退款 支付宝支付退款结果==============================' . json_encode($result));
        //使用重写的Response类、RedirectResponse、Collection类
        if ($result instanceof \Symfony\Component\HttpFoundation\RedirectResponse) {
            $result = RedirectResponse::create($result->getTargetUrl());
        } elseif ($result instanceof \Symfony\Component\HttpFoundation\Response) {
            $result = Response::create($result->getContent());
        } elseif ($result instanceof \Yansongda\Supports\Collection) {
            $result = yan_collection::make($result->all());
        }
        return $result;
    }
}
